<template>
  <SwipePagination v-model="page" :can-swipe="page !== 1">
    <PopularList :items="dataList" @pick="onPick" @intersect="nextPage"></PopularList>
    <template #page-2>
      <Viewer :router="viewerRouter"></Viewer>
    </template>
  </SwipePagination>
</template>

<script setup>
import { defineAsyncComponent, ref, watch } from 'vue'
import { useNavRefresh } from '@/compositions/nav/refresh'
import { useInfinite } from '@/compositions/request/infinite'
import { useMobileViewerRouter } from '@/compositions/viewer/router/mobileViewerRouter'
import { MEDIA_TYPE, NAVS } from '@/constant'
import { MEDIA_TOGGLE_TYPE } from '@/constant/viewer-router'
import API from '@/http'

const SwipePagination = defineAsyncComponent(() => import('@/components/swipe/SwipePagination.vue'))
const PopularList = defineAsyncComponent(() => import('@/components/home/PopularList.vue'))
const Viewer = defineAsyncComponent(() => import('@/components/viewer/Viewer.vue'))

const props = defineProps({
  refreshTimestamp: { type: Number },
})

const emits = defineEmits(['change:fpar'])

const page = ref(1)

const { dataList, loading, noMore, errorMsg, init, refresh, nextPage } = useInfinite({
  request: API.Media.getPopularSetList,
})
init()

const viewerRouter = useMobileViewerRouter('mobile-home-popular')
const { active, fpar, setFromMainViewer } = viewerRouter

watch(
  fpar,
  (v) => {
    emits('change:fpar', v)
  },
  { immediate: true },
)

let prevHotDate
function onPick(hotDate) {
  if (prevHotDate === hotDate) {
    page.value = 2
    return
  }

  prevHotDate = hotDate

  const fetcher = {
    video: useInfinite({
      request: API.Media.getPopularSet,
      params: { type: MEDIA_TYPE.VIDEO, hot_date: hotDate },
    }),
    photo: useInfinite({
      request: API.Media.getPopularSet,
      params: { type: MEDIA_TYPE.PHOTO, hot_date: hotDate },
    }),
  }

  setFromMainViewer(fetcher, MEDIA_TOGGLE_TYPE.SWITCHER)

  page.value = 2
}

watch(
  () => props.refreshTimestamp,
  () => {
    page.value = 1
  },
)

// 主頁不在第1頁 viewer 才被 active
watch(
  page,
  (newPage) => {
    active.value = newPage > 1
  },
  { immediate: true },
)

// nav 點擊原本頁面刷新
useNavRefresh(NAVS.HOME, () => {
  refresh()
  page.value = 1
})
</script>
